package com.chagee.store.operation.server.service.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chagee.base.utils.*;
import com.chagee.personnel.api.event.bo.PersonnelInfo;
import com.chagee.store.operation.api.bo.OrderExtJsonBO;
import com.chagee.store.operation.api.enums.*;
import com.chagee.store.operation.api.request.*;
import com.chagee.store.operation.api.response.SearchSupplierResponse;
import com.chagee.store.operation.api.response.WorkOrderResponse;
import com.chagee.store.operation.common.constant.CommonConstant;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import com.chagee.store.operation.common.utils.CommonUtil;
import com.chagee.store.operation.common.utils.ResponseUtil;
import com.chagee.store.operation.server.component.ReportExportCellWriteHandler;
import com.chagee.store.operation.server.entity.*;
import com.chagee.store.operation.server.event.dao.StoreDetailMapper;
import com.chagee.store.operation.server.event.dao.WorkOrderMapper;
import com.chagee.store.operation.server.event.service.*;
import com.chagee.store.operation.server.model.bo.*;
import com.chagee.store.operation.server.model.param.BatchUpdatePenalizeParam;
import com.chagee.store.operation.server.model.param.WorkOrderDetailRequest;
import com.chagee.store.operation.server.model.vo.*;
import com.chagee.store.operation.server.service.base.StoreBaseService;
import com.chagee.store.operation.server.service.base.StoreDetailBaseService;
import com.chagee.store.operation.server.service.biz.other.BatchUpdatePenalizeListener;
import com.chagee.store.operation.server.service.third.FeiShuSendService;
import com.chagee.store.operation.server.service.third.OssThirdService;
import com.chagee.store.operation.server.transfer.WorkOrderTransfer;
import com.chagee.store.operation.server.utils.DateUtil;
import com.chagee.storeManagement.api.event.enums.Product3SalesEnum;
import com.chagee.storeManagement.api.event.request.OperateRecordRequest;
import com.chagee.storeManagement.api.event.request.QueryOperateRecordInfoRequest;
import com.chagee.storeManagement.api.event.response.BasePageResponse;
import com.chagee.storeManagement.api.event.response.QueryStoreOperateRecordResponse;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.personnel.auth.service.PersonnelAuthService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.dubbo.rpc.RpcContext;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @ClassName WorkOrderBizService  //类名称
 * @Description: //类描述
 * @Author: Jacky-zhan	//作者
 * @CreateDate: 2024/7/3 17:52	//创建时间
 * @UpdateUser: Jacky-zhan  //变更者
 * @UpdateDate: 2024/7/3 17:52	//更新时间
 * @UpdateRemark: //更新的信息
 * @Version: 1.0    //版本号
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WorkOrderBizService {

	@Resource
	private WorkOrderTransfer workOrderTransfer;

	@Resource
	private WorkOrderBaseService workOrderBaseService;

	@Resource
	private WorkOrderMapper workOrderMapper;

	@Resource
	private StoreBaseService storeBaseService;

	@Resource
	private StoreDetailBaseService storeDetailBaseService;

	@Resource
	private StoreDetailMapper storeDetailMapper;

	@Resource
	private TaskExecutionBaseService taskExecutionBaseService;

	@Resource
	private StoreConfigurationBaseService storeConfigurationBaseService;

	@Resource
	private WorkOrderReceiverBaseService workOrderReceiverBaseService;

	@Resource
	private FeiShuMessageBizService feiShuMessageBizService;

	@Resource
	private AppealReviewerConfigurationBaseService addAppealReviewerBaseService;

	@Resource
	private OssThirdService ossThirdService;

	@Resource
	private PersonnelAuthService personnelAuthService;

	@Resource
	private FeiShuSendService feiShuSendService;

	private static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

	@Value("${orderExpire.handleExpire:24}")
	private Long handleExpire;

	@Value("${orderExpire.hours:48}")
	private Long orderExpire;

	private static final int EXPORT_PAGE_SIZE = 200;

	@Resource
	private OperateRecordBizService operateRecordBizService;

	@Resource
	private SupplierDetailBizService supplierDetailBizService;

	/**
	 * 开早打样工单详情
	 *
	 * @param request 工单编号
	 * @return 工单信息
	 */
	public WorkOrderResponse queryDetail(WorkOrderDetailRequest request) {
		WorkOrderResponse workOrderResponse = new WorkOrderResponse();
		if (Objects.isNull(request)) {
			throw new BizException(BizErrorCode.PARAMETER_IS_NULL);
		}
		String workOrderNumber = request.getWorkOrderNumber();
		//工单基础信息
		LambdaQueryWrapper<WorkOrderDO> workOrderDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
		workOrderDOLambdaQueryWrapper
			.eq(WorkOrderDO::getWorkOrderNumber, workOrderNumber)
			.eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		WorkOrderDO workOrderDO = workOrderBaseService.getOne(workOrderDOLambdaQueryWrapper);
		if (Objects.isNull(workOrderDO)) {
			throw new BizException(BizErrorCode.NO_WORK_ORDER_DATA);
		}
		BeanUtils.copyProperties(workOrderDO, workOrderResponse);
		if (workOrderDO.getReceiver() != null && workOrderDO.getReceiverMobile() != null) {
			String[] receiver = workOrderDO.getReceiver().split(",");

			String[] receiverMobile = workOrderDO.getReceiverMobile().split(",");
			List<String> encryptPhoneList = new ArrayList<>();
			for (String phone : receiverMobile) {
				String phoneNumber = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
				encryptPhoneList.add(phoneNumber);
			}
			receiverMobile = encryptPhoneList.toArray(new String[0]);
			String result = joinStringArrays(receiver, receiverMobile);
			workOrderResponse.setReceiverAndReceiverMobile(result);
		}
		if (StringUtils.isEmpty(workOrderDO.getExtra())) {
			OrderExtJsonBO penalizeExtBO = JSON.parseObject(workOrderDO.getExtra(), new TypeReference<OrderExtJsonBO>() {
			});
			workOrderResponse.setPenalizeExtBO(penalizeExtBO);
		}
		return workOrderResponse;
	}

	private static String joinStringArrays(String[] name, String[] phone) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < name.length; i++) {
			sb.append(name[i]).append("(").append(phone[i % phone.length]).append("),");
		}
		return sb.deleteCharAt(sb.lastIndexOf(",")).toString();
	}

	//查询供应商 下拉框
	public List<String> distinctSupplier() {
		QueryWrapper<WorkOrderDO> queryWrapper = new QueryWrapper<>();
		queryWrapper.select("DISTINCT supplier");
		queryWrapper.isNotNull("supplier");
		List<WorkOrderDO> workOrderDOList = workOrderBaseService.list(queryWrapper);
		List<String> result = new ArrayList<>();
		for (WorkOrderDO workOrderDO : workOrderDOList) {
			result.add(workOrderDO.getSupplier());
		}
		return result;
	}

	//工单表条件查询
	public PaginationData<WorkOrderResponse> query(PaginationRequest<WorkOrderRequest> request){
		PersonnelInfo loginUser = new PersonnelInfo();
		try {
			loginUser = personnelAuthService.getLoginUserInfoInWeb();
		} catch (Exception e) {
			//兼容提供给供应商接口调用
			String loginUserId = RpcContext.getContext().getAttachment("curLoginUserId");
			if (StringUtils.isNotBlank(loginUserId)) {
				loginUser.setId(Long.valueOf(loginUserId));
			}
		}
		log.info("addAppealReviewer#getLoginUserInfoInWeb:{}",loginUser);
		Page<WorkOrderDO> page = new Page<>(request.getPageNum(), request.getPageSize());

		WorkOrderRequest workOrderRequest = request.getQueryParameter();
		Page<WorkOrderDO> workOrderDOS = queryWorkOrderPage(page, workOrderRequest);

		if (CollectionUtils.isEmpty(workOrderDOS.getRecords())) {
			return ResponseUtil.emptyResponse(request, WorkOrderResponse.class, workOrderDOS.getTotal());
		}
		List<WorkOrderDO> workOrderDOList = workOrderDOS.getRecords();

		List<SearchSupplierResponse> supplierList = supplierDetailBizService.supplierList();
		Map<String, String> supplierMap = supplierList.stream().filter(s -> StringUtils.isNotBlank(s.getCode())).collect(Collectors.toMap(SearchSupplierResponse::getCode, SearchSupplierResponse::getName, (a, b) -> b));

		List<String> storeNoList = workOrderDOList.stream().map(WorkOrderDO::getStoreCode).collect(Collectors.toList());

		List<StoreConfigurationDO> storeConfigurationDOS = storeConfigurationBaseService.batchGetByStoreCodeList(storeNoList);
		Map<String, StoreConfigurationDO> storeConfigurationDOMap = storeConfigurationDOS.stream().collect(Collectors.toMap(StoreConfigurationDO::getStoreCode, Function.identity(), (a, b) -> a));

		List<String> orderNos = workOrderDOList.stream().map(WorkOrderDO::getWorkOrderNumber).collect(Collectors.toList());
		List<TaskExecutionDO> taskExecutionDOS = taskExecutionBaseService.queryTaskList(orderNos);
		Map<String, List<TaskExecutionDO>> taskExecutionMap = taskExecutionDOS.stream().collect(Collectors.groupingBy(TaskExecutionDO::getWorkOrderNumber));


		List<StoreDetailBO> storeDetailBOS = storeDetailMapper.selectListByStoreNos(storeNoList);
		Map<String, StoreDetailBO> map = storeDetailBOS.stream().collect(Collectors.toMap(StoreDetailBO::getStoreNo, Function.identity(), (a, b) -> b));
		for (Map.Entry<String, StoreDetailBO> entry : map.entrySet()) {
			StoreDetailBO storeDetailBO = entry.getValue();
			String code = storeDetailBO.getRegion().split(CommonConstant.OR_STRING)[1];
			List<AppealReviewerConfigurationDO> configurationDOS = addAppealReviewerBaseService.queryByRegion(code);
			if (CollectionUtil.isEmpty(configurationDOS)) {
				storeDetailBO.setIfSetting(false);
			}
		}

		LambdaQueryWrapper<WorkOrderReceiverDO> queryWrapper = new LambdaQueryWrapper();
		queryWrapper.in(WorkOrderReceiverDO::getWorkOrderNumber, orderNos);
		List<WorkOrderReceiverDO> orderReceiverDOS = workOrderReceiverBaseService.list(queryWrapper);
		Map<String, List<WorkOrderReceiverDO>> listMap = orderReceiverDOS.stream().collect(Collectors.groupingBy(WorkOrderReceiverDO::getWorkOrderNumber));

		Set<Integer> regions = Sets.newHashSet();
		if (Objects.nonNull(loginUser.getId())) {
			List<AppealReviewerConfigurationDO> appealReviewerDOS = addAppealReviewerBaseService.queryByReveiwerId(String.valueOf(loginUser.getId()));
			if (CollectionUtil.isNotEmpty(appealReviewerDOS)) {
				List<String> regionList = appealReviewerDOS.stream().map(AppealReviewerConfigurationDO::getCityRegion).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
				regions = getRegion(regionList);
			}
		}
		List<WorkOrderResponse> workOrderResponseList = new LinkedList<>();
		for (WorkOrderDO workOrderDO : workOrderDOS.getRecords()) {
			WorkOrderResponse workOrderResponse = new WorkOrderResponse();
			BeanUtils.copyProperties(workOrderDO,workOrderResponse);
			if(workOrderDO.getReceiver()!=null&&workOrderDO.getReceiverMobile()!=null){
				String[] receiver = workOrderDO.getReceiver().split(",");

				String[] receiverMobile = workOrderDO.getReceiverMobile().split(",");
				List<String> encryptPhoneList = new ArrayList<>();
				for (String phone : receiverMobile) {
					String phoneNumber = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
					encryptPhoneList.add(phoneNumber);
				}
				receiverMobile = encryptPhoneList.toArray(new String[0]);
				String result = joinStringArrays(receiver, receiverMobile);
				workOrderResponse.setReceiverAndReceiverMobile(result);
			}
			//添加3.0产品售卖情况
			if (MapUtil.isNotEmpty(map) && null != map.get(workOrderDO.getStoreCode())){
				Product3SalesEnum product3SalesEnum = Product3SalesEnum.of(map.get(workOrderDO.getStoreCode()).getProductThridSalesStatus());
				if (Objects.nonNull(product3SalesEnum)) {
					workOrderResponse.setProductThridSalesStatus(product3SalesEnum.getInfo());
				}
			}
			if (StringUtils.isNotBlank(workOrderDO.getDocumentScore())) {
				workOrderResponse.setIsQualified(Integer.parseInt(workOrderDO.getDocumentScore()) < 80 ? OrderAcceptanceEnum.NO.name() : OrderAcceptanceEnum.YES.name());
			}
			//单个工单对应一个供应商
			if (MapUtil.isNotEmpty(listMap) && CollectionUtils.isNotEmpty(listMap.get(workOrderDO.getWorkOrderNumber()))) {
				WorkOrderReceiverDO workOrderReceiverDO = listMap.get(workOrderDO.getWorkOrderNumber()).stream().findFirst().orElse(null);
				if (Objects.nonNull(workOrderReceiverDO)) {
					workOrderResponse.setSupplierId(workOrderReceiverDO.getSupplierId());
				}
			}
			if (StringUtils.isNotBlank(workOrderDO.getExtra())){
				OrderExtJsonBO orderExtJsonBOS = JSONObject.parseObject(workOrderDO.getExtra(), OrderExtJsonBO.class);
				workOrderResponse.setPenalizeExtBO(orderExtJsonBOS);
			}
			if (MapUtil.isNotEmpty(map) && Objects.nonNull(map.get(workOrderDO.getStoreCode()))) {
				String region = map.get(workOrderDO.getStoreCode()).getRegion();
				String code = region.split(CommonConstant.OR_STRING)[1]; // 该工单门店所属 市
				if (regions.contains(Integer.parseInt(code))) {
					workOrderResponse.setHandleAppealButton(true);
				}
				if (Boolean.FALSE.equals(map.get(workOrderDO.getStoreCode()).getIfSetting())) {
					workOrderResponse.setHandleAppealButton(true);
				}
			}
			boolean orderExpiredFlag = false;
			if (Objects.nonNull(workOrderDO.getExpiredTime())) {
				//工单过期申述有效期 48小时
				orderExpiredFlag = DateUtil.getOrderExpiredDate(workOrderDO.getExpiredTime(), orderExpire);
			}
			if (StringUtils.isNotBlank(workOrderDO.getAppealResult()) && OrderAppealStatusEnum.N.getType().equals(workOrderDO.getAppealResult())) {
				orderExpiredFlag = false;
			}
			workOrderResponse.setOrderExpiredFlag(orderExpiredFlag);

			if (MapUtil.isNotEmpty(storeConfigurationDOMap) && Objects.nonNull(storeConfigurationDOMap.get(workOrderDO.getStoreCode()))) {
				StoreConfigurationDO storeConfigurationDO = storeConfigurationDOMap.get(workOrderDO.getStoreCode());
				workOrderResponse.setFloorPrice(getOrderFloorPrice(workOrderDO, storeConfigurationDO.getFloorPrice()));
				workOrderResponse.setBillingStartDate(storeConfigurationDO.getBillingStartDate());
			}

			List<TaskExecutionDO> executionDOS = taskExecutionMap.get(workOrderDO.getWorkOrderNumber());
			String workOrderRemark = this.getWorkOrderRemark(executionDOS);
			workOrderResponse.setRemark(workOrderRemark);

			if (MapUtil.isNotEmpty(supplierMap) && StringUtils.isNotBlank(supplierMap.get(workOrderDO.getSupplierNo()))) {
				workOrderResponse.setSupplier(supplierMap.get(workOrderDO.getSupplierNo()));
			}

			workOrderResponseList.add(workOrderResponse);
		}
		return ResponseUtil.commonResponse(request, workOrderResponseList, workOrderDOS.getTotal());
	}

	private String getWorkOrderRemark(List<TaskExecutionDO> executionDOS ) {
		String remark = StringUtils.EMPTY;
		if (CollectionUtils.isNotEmpty(executionDOS)) {
			List<TaskExecutionDO> noTasK = executionDOS.stream().filter(s -> StringUtils.isNotBlank(s.getEarlyAcceptance()) && StoreTaskEnum.NO.getType().equals(s.getEarlyAcceptance())).collect(Collectors.toList());
			if (CollectionUtils.isNotEmpty(noTasK)) {
				StringBuilder builderRemark = new StringBuilder();
				for (TaskExecutionDO taskExecutionDO : noTasK) {
					builderRemark.append(taskExecutionDO.getTaskName()).append(":").append(StringUtils.isNotBlank(taskExecutionDO.getRemark()) ? taskExecutionDO.getRemark() : "").append("\n");
				}
				remark = builderRemark.toString();
			}
		}
		return remark;
	}


	//获取市
	public Set<Integer> getRegion(List<String> cityList) {
		Set<Integer> cityRegionList = Sets.newHashSet();

		Set<String> strings = Sets.newHashSet();
		cityList.forEach(s -> {
			//["123,4324","123,4324"]
			List<String> lists = JSONObject.parseArray(s, String.class);
			strings.addAll(lists);
		});
		if (CollectionUtil.isNotEmpty(strings)) {
			for (String code : strings) {
				if (StringUtils.isNotBlank(code)) {
					String[] regionCode = code.split(CommonConstant.OR_STRING);
					if (regionCode.length > 0) {
						cityRegionList.add(Integer.parseInt(regionCode[1]));
					}
				}
			}
		}
		return cityRegionList;
	}

	//工单导出  todo ? 文件名乱码?
	@SneakyThrows
	public void export(WorkOrderRequest requestParam, HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		//List<WorkOrderResponse> workOrderResponseList = this.queryWorkOrderByPage(requestParam);
		if (Objects.isNull(requestParam) || StringUtils.isBlank(requestParam.getCreateTimeStart()) || StringUtils.isBlank(requestParam.getCreateTimeEnd())) {
			throw new BizException(BizErrorCode.EXPORT_DATE_FAIL);
		}
		if (!DateUtil.getDistanceDate(requestParam.getCreateTimeStart(),requestParam.getCreateTimeEnd())) {
			throw new BizException(BizErrorCode.EXPORT_DISTANCE_DATE_FAIL);
		}

		List<SearchSupplierResponse> supplierList = supplierDetailBizService.supplierList();
		Map<String, String> supplierMap = supplierList.stream().filter(s -> StringUtils.isNotBlank(s.getCode())).collect(Collectors.toMap(SearchSupplierResponse::getCode, SearchSupplierResponse::getName, (a, b) -> b));


		CommonUtil.download(response, CommonConstant.THIRD_WORK_ORDER);
		try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), WorkOrderExcelVO.class).build()) {
			WriteSheet writeSheet = EasyExcel.writerSheet(CommonConstant.THIRD_WORK_ORDER).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
				.registerWriteHandler(new ReportExportCellWriteHandler(CommonConstant.THIRD_WORK_ORDER)).build();

			List<WorkOrderResponse> workOrderResponses;
			List<WorkOrderExcelVO> workOrderExcelVoList;

			long startIndex = 0L;
			while (true) {
				requestParam.setId(startIndex);
				LambdaQueryWrapper<WorkOrderDO> queryWrapper = builderQueryWrapper(requestParam);
				queryWrapper.orderByAsc(WorkOrderDO::getId);
				queryWrapper.last(CommonConstant.LIMIT_SIZE_SQL);
				List<WorkOrderDO> workOrderDOS = workOrderBaseService.list(queryWrapper);

				if (CollectionUtils.isEmpty(workOrderDOS)) {
					excelWriter.write(new ArrayList<WorkOrderExcelVO>(), writeSheet);
					break;
				}
				workOrderResponses = queryWorkOrderByPage(workOrderDOS, supplierMap);
				workOrderExcelVoList = workOrderTransfer.workOrderResponse2WorkOrderExcelVOList(workOrderResponses);
				excelWriter.write(workOrderExcelVoList, writeSheet);
				startIndex = Math.toIntExact(workOrderDOS.stream().map(WorkOrderDO::getId).max(Comparator.naturalOrder()).orElse(0L));
			}
		} catch (ExcelGenerateException e) {
			log.error("WorkOrderBizService_export导出异常", e);
		}
		//excel表头
//		List<WorkOrderExcelVO> workOrderExcelVoList = new ArrayList<>();
//		String time = DATE_TIME_FORMAT.format(LocalDateTime.now());
//		if (CollUtil.isNotEmpty(workOrderResponseList)) {
//			//数据库 数据
//
//			// List<workOrderResponse> to List<WorkOrderExcelVOList>
//			workOrderExcelVoList = workOrderTransfer.workOrderResponse2WorkOrderExcelVOList(workOrderResponseList);
//		}
//		ExportParams params = new ExportParams(CommonConstant.THIRD_WORK_ORDER, CommonConstant.THIRD_WORK_ORDER, ExcelType.XSSF);
//		//导出时排除一些字段
//		params.setExclusions(new String[]{});
//
//		// 设置响应头
//		response.setCharacterEncoding("UTF-8");
//		try {
//			String fileName = URLEncoder.encode(CommonConstant.THIRD_WORK_ORDER +"_"+ time, "UTF-8").replaceAll("\\+", "%20");
//			response.setHeader("Content-disposition", "attachment;filename=" + fileName +".xlsx");
//			map.put(NormalExcelConstants.DATA_LIST, workOrderExcelVoList);
//			map.put(NormalExcelConstants.CLASS, WorkOrderExcelVO.class);
//			map.put(NormalExcelConstants.PARAMS, params);
//			map.put(NormalExcelConstants.FILE_NAME, fileName);
//		} catch (UnsupportedEncodingException e) {
//			log.error("exportStoreOrder() called with exception => 【requestParam = {}】, 【request = {}】, 【response = {}】, 【map = {}】", requestParam, request, response, map, e);
//			throw new BizException(BizErrorCode.DOWNLOAD_EXCEL_FAIL);
//		}
//		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//
//		PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);

	}

	public LambdaQueryWrapper<WorkOrderDO> builderQueryWrapper(WorkOrderRequest workOrderRequest) {
		LambdaQueryWrapper<WorkOrderDO> wrapper = new LambdaQueryWrapper();
		if(workOrderRequest!=null){
			if(Objects.nonNull(workOrderRequest.getId())){
				wrapper.gt(WorkOrderDO::getId, workOrderRequest.getId());
			}
			if(StringUtils.isNotBlank(workOrderRequest.getWorkOrderNumber())){
				wrapper.like(WorkOrderDO::getWorkOrderNumber,workOrderRequest.getWorkOrderNumber());
			}
			if(StringUtils.isNotBlank(workOrderRequest.getStoreCode())){
				wrapper.like(WorkOrderDO::getStoreCode,workOrderRequest.getStoreCode());
			}
			if(StringUtils.isNotBlank(workOrderRequest.getStoreName())){
				wrapper.like(WorkOrderDO::getStoreName,workOrderRequest.getStoreName());
			}
			/*if(workOrderRequest.getReceiver()!=null){
				wrapper.like(WorkOrderDO::getReceiver,workOrderRequest.getReceiver()).or().like(WorkOrderDO::getReceiverMobile,workOrderRequest.getReceiver());
			}*/
			if(StringUtils.isNotBlank(workOrderRequest.getReceiver())){
				wrapper.and(wq->wq.like(WorkOrderDO::getReceiver,workOrderRequest.getReceiver())
					.or().like(WorkOrderDO::getReceiverMobile,workOrderRequest.getReceiver()));
			}
			if(StringUtils.isNotBlank(workOrderRequest.getDocumentStatus())){
				wrapper.eq(WorkOrderDO::getDocumentStatus,workOrderRequest.getDocumentStatus());
			}
			if(StringUtils.isNotBlank(workOrderRequest.getSupplier())){
				wrapper.like(WorkOrderDO::getSupplier,workOrderRequest.getSupplier());
			}
			if(StringUtils.isNotBlank(workOrderRequest.getSupplierNo())){
				wrapper.eq(WorkOrderDO::getSupplierNo,workOrderRequest.getSupplierNo());
			}
			if(StringUtils.isNotBlank(workOrderRequest.getStoreCategory())){
				wrapper.eq(WorkOrderDO::getStoreCategory,workOrderRequest.getStoreCategory());
			}
			if(StringUtils.isNotBlank(workOrderRequest.getCreateTimeStart())){
				wrapper.ge(WorkOrderDO::getCreateTime,workOrderRequest.getCreateTimeStart());
			}
			if(StringUtils.isNotBlank(workOrderRequest.getCreateTimeEnd())){
				wrapper.le(WorkOrderDO::getCreateTime,workOrderRequest.getCreateTimeEnd());
			}
			if (StringUtils.isNotBlank(workOrderRequest.getCompanyName()) ) {
				wrapper.eq(WorkOrderDO::getCompanyName, workOrderRequest.getCompanyName());
			}
			if (StringUtils.isNotBlank(workOrderRequest.getIsQualified())) {
				if (OrderAcceptanceEnum.YES.name().equals(workOrderRequest.getIsQualified())) {
					wrapper.ge(WorkOrderDO::getDocumentScore, 80);
				} else if (OrderAcceptanceEnum.NO.name().equals(workOrderRequest.getIsQualified())) {
					wrapper.lt(WorkOrderDO::getDocumentScore, 80);
				}
			}
			if (StringUtils.isNotBlank(workOrderRequest.getAcceptanceType())) {
				wrapper.eq(WorkOrderDO::getAcceptanceType, workOrderRequest.getAcceptanceType());
			}
			if (StringUtils.isNotBlank(workOrderRequest.getAppealFlag())) {
				wrapper.eq(WorkOrderDO::getAppealFlag, workOrderRequest.getAppealFlag());
			}
			// 供应商列表展示(待交接,待接单) 工单  主账号
//			if (StringUtils.isBlank(workOrderRequest.getWorkOrderNumber()) && StringUtils.isBlank(workOrderRequest.getStoreCode()) && StringUtils.isBlank(workOrderRequest.getDocumentStatus()) && StringUtils.isBlank(workOrderRequest.getCompanyName())
//				&& StringUtils.isBlank(workOrderRequest.getIsQualified()) && StringUtils.isBlank(workOrderRequest.getReceiver()) && StringUtils.isBlank(workOrderRequest.getCreateTimeStart()) && StringUtils.isBlank(workOrderRequest.getCreateTimeEnd())) {
//				if (UserTypeEnum.MASTER.getType().equals(workOrderRequest.getUserType())) {
//					wrapper.or(s -> s.in(WorkOrderDO::getDocumentStatus, Arrays.asList(StoreWorkOrderStatusEnum.TO_BE_HANDED_OVER.getType(),StoreWorkOrderStatusEnum.PENDING_ORDERS.getType())));
//				}
//			}
		}
		return wrapper;
	}

	public Page<WorkOrderDO> queryWorkOrderPage(Page<WorkOrderDO> page, WorkOrderRequest workOrderRequest) {
		LambdaQueryWrapper<WorkOrderDO> wrapper = builderQueryWrapper(workOrderRequest);
		if(workOrderRequest!=null){
			wrapper.orderByDesc(WorkOrderDO::getId).orderByDesc(WorkOrderDO::getStoreCode);
		}
		Page<WorkOrderDO> workOrderDOS = workOrderMapper.selectPage(page,wrapper);

		return workOrderDOS;
	}

	//工单表条件查询导出
	public List<WorkOrderResponse> queryWorkOrderByPage(List<WorkOrderDO> workOrderDOS, Map<String, String> supplierMap) {
//		LambdaQueryWrapper<WorkOrderDO> wrapper = new LambdaQueryWrapper();
//		if (workOrderRequest != null) {
//			if (workOrderRequest.getWorkOrderNumber() != null) {
//				wrapper.like(WorkOrderDO::getWorkOrderNumber, workOrderRequest.getWorkOrderNumber());
//			}
//			if (workOrderRequest.getStoreCode() != null) {
//				wrapper.like(WorkOrderDO::getStoreCode, workOrderRequest.getStoreCode());
//			}
//			if (StringUtils.isNotBlank(workOrderRequest.getStoreName())) {
//				wrapper.like(WorkOrderDO::getStoreName, workOrderRequest.getStoreName());
//			}
//			if (workOrderRequest.getReceiver() != null) {
//				wrapper.like(WorkOrderDO::getReceiver, workOrderRequest.getReceiver());
//			}
//			if (workOrderRequest.getDocumentStatus() != null) {
//				wrapper.eq(WorkOrderDO::getDocumentStatus, workOrderRequest.getDocumentStatus());
//			}
//			if (workOrderRequest.getSupplier() != null) {
//				wrapper.like(WorkOrderDO::getSupplier, workOrderRequest.getSupplier());
//			}
//			if (workOrderRequest.getStoreCategory() != null) {
//				wrapper.eq(WorkOrderDO::getStoreCategory, workOrderRequest.getStoreCategory());
//			}
//			if (workOrderRequest.getCreateTimeStart() != null) {
//				wrapper.ge(WorkOrderDO::getCreateTime, workOrderRequest.getCreateTimeStart());
//			}
//			if (workOrderRequest.getCreateTimeEnd() != null) {
//				wrapper.le(WorkOrderDO::getCreateTime, workOrderRequest.getCreateTimeEnd());
//			}
//			if (workOrderRequest.getCompanyName() != null) {
//				wrapper.eq(WorkOrderDO::getCompanyName, workOrderRequest.getCompanyName());
//			}
//			if (workOrderRequest.getIsQualified() != null) {
//				if (OrderAcceptanceEnum.YES.name().equals(workOrderRequest.getIsQualified())) {
//					wrapper.ge(WorkOrderDO::getDocumentScore, 80);
//				} else if (OrderAcceptanceEnum.NO.name().equals(workOrderRequest.getIsQualified())) {
//					wrapper.lt(WorkOrderDO::getDocumentScore, 80);
//				}
//			}
//			if (StringUtils.isNotBlank(workOrderRequest.getAcceptanceType())) {
//				wrapper.eq(WorkOrderDO::getAcceptanceType, workOrderRequest.getAcceptanceType());
//			}
//		}
//		List<WorkOrderDO> workOrderDOS = workOrderBaseService.list(wrapper);
		if (CollectionUtils.isEmpty(workOrderDOS)) {
			return new ArrayList<>();
		}
		List<String> storeNoList = workOrderDOS.stream().map(WorkOrderDO::getStoreCode).collect(Collectors.toList());
		List<StoreDetailBO> storeDetailBOS = storeDetailMapper.selectListByStoreNos(storeNoList);
		Map<String, StoreDetailBO> map = storeDetailBOS.stream().collect(Collectors.toMap(StoreDetailBO::getStoreNo, Function.identity(), (a, b) -> b));

		LambdaQueryWrapper<StoreConfigurationDO> queryWrapper = new LambdaQueryWrapper();
		queryWrapper.in(StoreConfigurationDO::getStoreCode, storeNoList);
		List<StoreConfigurationDO> list = storeConfigurationBaseService.list(queryWrapper);
		Map<String, StoreConfigurationDO> configurationDOMap = list.stream().collect(Collectors.toMap(StoreConfigurationDO::getStoreCode, Function.identity(), (a, b) -> a));

		LambdaQueryWrapper<TaskExecutionDO> lambdaQueryWrapper = new LambdaQueryWrapper();
		lambdaQueryWrapper.in(TaskExecutionDO::getWorkOrderNumber, workOrderDOS.stream().map(WorkOrderDO::getWorkOrderNumber).collect(Collectors.toList()));
		List<TaskExecutionDO> taskExecutionDOS = taskExecutionBaseService.list(lambdaQueryWrapper);
		Map<String, List<TaskExecutionDO>> stringListMap = taskExecutionDOS.stream().collect(Collectors.groupingBy(TaskExecutionDO::getWorkOrderNumber));

		List<WorkOrderResponse> workOrderResponseList = new LinkedList<>();
		for (WorkOrderDO workOrderDO : workOrderDOS) {
			WorkOrderResponse workOrderResponse = new WorkOrderResponse();
			BeanUtils.copyProperties(workOrderDO, workOrderResponse);
			if (StringUtils.isNotBlank(workOrderDO.getReceiver()) && StringUtils.isNotBlank(workOrderDO.getReceiverMobile())) {
				String[] receiver = workOrderDO.getReceiver().split(",");
				String[] receiverMobile = workOrderDO.getReceiverMobile().split(",");

				List<String> encryptPhoneList = new ArrayList<>();
				for (String phone : receiverMobile) {
					String phoneNumber = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
					encryptPhoneList.add(phoneNumber);
				}
				receiverMobile = encryptPhoneList.toArray(new String[0]);
				String result = joinStringArrays(receiver, receiverMobile);
				workOrderResponse.setReceiverAndReceiverMobile(result);
			}

			//添加3.0产品售卖情况
			if (MapUtil.isNotEmpty(map) && null != map.get(workOrderDO.getStoreCode())){
				Product3SalesEnum product3SalesEnum = Product3SalesEnum.of(map.get(workOrderDO.getStoreCode()).getProductThridSalesStatus());
				if (Objects.nonNull(product3SalesEnum)) {
					workOrderResponse.setProductThridSalesStatus(product3SalesEnum.getInfo());
				}
			}
			if (StringUtils.isNotBlank(workOrderDO.getDocumentScore())) {
				workOrderResponse.setIsQualified(Integer.parseInt(workOrderDO.getDocumentScore()) < 80 ? "否" : "是");
			}
			List<TaskExecutionDO> executionDOS = stringListMap.get(workOrderDO.getWorkOrderNumber());
			if (CollectionUtils.isNotEmpty(executionDOS)) {
				List<TaskExecutionDO> noTasK = executionDOS.stream().filter(s -> StringUtils.isNotBlank(s.getEarlyAcceptance()) && StoreTaskEnum.NO.getType().equals(s.getEarlyAcceptance())).collect(Collectors.toList());
				if (CollectionUtils.isNotEmpty(noTasK)) {
					StringBuilder builderRemark = new StringBuilder();
					StringBuilder builderPicture = new StringBuilder();
					for (TaskExecutionDO taskExecutionDO : noTasK) {
						builderRemark.append(taskExecutionDO.getTaskName()).append(":").append(StringUtils.isNotBlank(taskExecutionDO.getRemark()) ? taskExecutionDO.getRemark() : "").append("\n");
						List<FileVO> voList = JSON.parseArray(taskExecutionDO.getRemarkPicture(), FileVO.class);
						List<String> filePathList = new ArrayList<>();
						if (CollectionUtils.isNotEmpty(voList)) {
							filePathList = voList.stream().filter(s -> s != null && StringUtils.isNotBlank(s.getFilePath())).map(FileVO::getFilePath).collect(Collectors.toList());
						}
						builderPicture.append(taskExecutionDO.getTaskName()).append(":").append(filePathList).append("\n");
					}
					workOrderResponse.setRemark(builderRemark.toString());
					workOrderResponse.setRemarkPicture(builderPicture.toString());
				}
			}
			//计费开始时间
			StoreConfigurationDO configurationDO = configurationDOMap.get(workOrderDO.getStoreCode());
			if (Objects.nonNull(configurationDO) && ObjectUtil.isNotEmpty(configurationDO.getBillingStartDate())) {
				workOrderResponse.setBillingStartDate(configurationDO.getBillingStartDate());
			}
			if (Objects.nonNull(configurationDO)) {
				//保留两位小数
				//String floorPrice = configurationDO.getFloorPrice().setScale(2, BigDecimal.ROUND_HALF_DOWN).toString();
				workOrderResponse.setFloorPrice(getOrderFloorPrice(workOrderDO, configurationDO.getFloorPrice()));
			}
			if (Objects.nonNull(configurationDO) && ObjectUtil.isNotEmpty(configurationDO.getNightFloorPrice())) {
				String nightFloorPrice = configurationDO.getNightFloorPrice().setScale(2, BigDecimal.ROUND_HALF_DOWN).toString();
				workOrderResponse.setNightFloorPrice(nightFloorPrice);
			}
			if (StringUtils.isNotBlank(workOrderDO.getAcceptanceType())) {
				workOrderResponse.setAcceptanceType(OrderAcceptanceTypeEnum.queryByType(workOrderDO.getAcceptanceType()).getDesc());
			}
			if (StringUtils.isNotBlank(workOrderDO.getAppealFlag())) {
				workOrderResponse.setAppealFlag(OrderAppealTypeEnum.getByType(workOrderDO.getAppealFlag()).getDesc());
			}

			if (MapUtil.isNotEmpty(supplierMap) && StringUtils.isNotBlank(supplierMap.get(workOrderDO.getSupplierNo()))) {
				workOrderResponse.setSupplier(supplierMap.get(workOrderDO.getSupplierNo()));
			}

			workOrderResponseList.add(workOrderResponse);
		}

		return workOrderResponseList;
	}

	private String getOrderFloorPrice(WorkOrderDO workOrderDO, BigDecimal floorPrice) {
		String orderFloorPrice = CommonConstant.NONE_STRING;

		// 产品:大于四月份默认显示当前的结算底价 (4/16)
		if (DateUtil.dateCompareTo(workOrderDO.getCreateTime())) {
			orderFloorPrice = Objects.nonNull(floorPrice) ? floorPrice.toPlainString() : CommonConstant.NONE_STRING;
		}
		if (StringUtils.isNotBlank(workOrderDO.getExtra())) {
			OrderExtJsonBO extJsonBO = JSON.parseObject(workOrderDO.getExtra(), new TypeReference<OrderExtJsonBO>() {
			});
			if (Objects.nonNull(extJsonBO.getFloorPrice())) {
				orderFloorPrice = extJsonBO.getFloorPrice().toPlainString();
			}
		}
		return orderFloorPrice;
	}

	public Boolean penalizeMoney(OrderPenalizeMoneyRequest request) {
		OrderExtJsonBO penalizeExtBO = new OrderExtJsonBO();
		penalizeExtBO.setRemark(request.getRemark());
		penalizeExtBO.setRemarkPic(request.getRemarkPic());
		workOrderBaseService.update(request, penalizeExtBO);
		return true;
	}


	/**
	 * 批量变更门店结算底价
	 * @param request req
	 * @return response
	 */
	public BatchUpdatePenalizeVO batchUpdatePenalizeMoney(BatchUpdatePenalizeParam request) {

		BatchUpdatePenalizeListener listener = new BatchUpdatePenalizeListener(storeBaseService);
		try {
			URL url = new URL(request.getUrl());
			EasyExcel.read(url.openStream(), listener).doReadAllSync();
		} catch (Exception e) {
			log.error("WorkOrderBizService_batchUpdatePenalizeMoney_read_excel_throw_exception.", e);
			throw new BizException(BizErrorCode.PROCESS_EXCEL_FILE_ERROR);
		}
		BatchUpdatePenalizeVO response = new BatchUpdatePenalizeVO();
		response.setTotalCount(listener.getTotal());

		response.setProcessResult(true);
		response.setSuccessCount(listener.getProcessSuccessTotal());
		response.setFailCount(listener.getProcessFailTotal());

		List<BatchUpdateSettlementErrBO> errWhenUpdate = new ArrayList<>();

		// 正常发起变更
		if (!org.springframework.util.CollectionUtils.isEmpty(listener.getOriginalList())) {
			errWhenUpdate = batchUpdate(listener.getOriginalList());
		}

		// 不IOssServiceApi支持修改数据
		if (!CollectionUtils.isEmpty(listener.getErrBOList()) || !CollectionUtils.isEmpty(errWhenUpdate)) {
			List<BatchUpdateSettlementErrBO> errBOList = listener.getErrBOList();
			errBOList.addAll(errWhenUpdate);
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			EasyExcel.write(outputStream, BatchUpdateSettlementErrBO.class)
				.sheet()
				.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
				.doWrite(errBOList);
			String filePath = ossThirdService.upload(outputStream.toByteArray(), UUID.randomUUID() + CommonConstant.XLSX);
			response.setProcessResult(false);
			response.setErrFilePath(filePath);
			// 处理变更过程中的异常数据条数
			response.setFailCount(listener.getProcessFailTotal() + errWhenUpdate.size());
			response.setSuccessCount(listener.getProcessSuccessTotal() - errWhenUpdate.size());
		}
		return response;
	}

	private List<BatchUpdateSettlementErrBO> batchUpdate(List<BatchUpdateSettlementBO> list) {
		if (CollectionUtils.isEmpty(list)) {
			return Lists.newArrayList();
		}
		List<BatchUpdateSettlementErrBO> errBOS = new ArrayList<>();

		for (BatchUpdateSettlementBO settlementBO : list) {
			try {
				storeConfigurationBaseService.updateStoreConfiguration(settlementBO);
			} catch (Exception e) {
				BatchUpdateSettlementErrBO errBO = new BatchUpdateSettlementErrBO();
				BeanUtil.copyProperties(settlementBO, errBO);
				errBO.setFailMsg(e.getMessage());
				errBOS.add(errBO);
				log.error("StoreBizService_batchUpdatePenalize_batchUpdate_err {}", settlementBO.getStoreNo(), e);
				continue;
			}
		}

		return errBOS;
	}

	public HttpResponse<Boolean> handleAppeal(StoreHandleAppealRequest request) {
		BladeUser user = AuthUtil.getUser();
		LambdaQueryWrapper<WorkOrderDO> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(WorkOrderDO::getWorkOrderNumber, request.getWorkOrderNumber())
			.eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		List<WorkOrderDO> list = workOrderBaseService.list(queryWrapper);

		WorkOrderDO workOrderDO = list.stream().findFirst().orElseThrow(() -> new BizException(BizErrorCode.ORDER_NOT_EXIST));
		if (Objects.isNull(workOrderDO) || !StoreWorkOrderStatusEnum.EXPIRED_APPEAL.getType().equals(workOrderDO.getDocumentStatus())) {
			return HttpResponseUtil.build(false, BizErrorCode.NO_WORK_ORDER_DATA.getErrorCode(), BizErrorCode.NO_WORK_ORDER_DATA.getErrorMsg());
		}

		//处理申诉24小时有效期
		if (Objects.nonNull(workOrderDO.getAppealTime())) {
			boolean handleFlag = DateUtil.getOrderExpiredDate(workOrderDO.getAppealTime(), handleExpire);
			if (!handleFlag) {
				return HttpResponseUtil.build(false, BizErrorCode.HANDLE_OVERTIME_FAIL.getErrorCode(), BizErrorCode.HANDLE_OVERTIME_FAIL.getErrorMsg());
			}
		}

		// 打烊任务连续三天不合格
		if (StringUtils.isNotBlank(workOrderDO.getContinuousAcceptance()) && OrderTaskAcceptanceEnum.NO_PASS.getType().equals(workOrderDO.getContinuousAcceptance())) {
			if (OrderAppealStatusEnum.Y.getType().equals(request.getAppealResult())) {
				workOrderDO.setDocumentStatus(StoreWorkOrderStatusEnum.COMPLETED.getType());
				workOrderDO.setAppealResult(OrderAppealStatusEnum.Y.getType());
				workOrderDO.setContinuousAcceptance(OrderTaskAcceptanceEnum.PASS.getType());
				//重新计算
				taskExecutionBaseService.calculateQualificationRate(workOrderDO);
			}else {
				workOrderDO.setAppealResult(OrderAppealStatusEnum.N.getType());
				workOrderDO.setDocumentStatus(StoreWorkOrderStatusEnum.COMPLETED.getType());
				workOrderDO.setContinuousAcceptance(OrderTaskAcceptanceEnum.APPEAL_REJECTED.getType());
			}
		}else  if (StoreWorkOrderStatusEnum.EXPIRED_APPEAL.getType().equals(workOrderDO.getDocumentStatus())){
			//工单过期申诉
			if (OrderAppealStatusEnum.Y.getType().equals(request.getAppealResult())) {
				workOrderDO.setDocumentStatus(StoreWorkOrderStatusEnum.COMPLETED.getType());
				workOrderDO.setAppealResult(OrderAppealStatusEnum.Y.getType());
				if (OrderAcceptanceEnum.YES.getType().equals(request.getIsQualified())) {
					workOrderDO.setDocumentScore("80");
				} else {
					workOrderDO.setDocumentScore("0");
				}
			}else {
				workOrderDO.setAppealResult(OrderAppealStatusEnum.N.getType());
				workOrderDO.setDocumentStatus(StoreWorkOrderStatusEnum.EXPIRED.getType());
			}
		}else {
			throw new BizException(BizErrorCode.ORDER_STATUS_FAIL);
		}

		OrderExtJsonBO extJsonBO = new OrderExtJsonBO();
		if (StringUtils.isNotBlank(workOrderDO.getExtra())) {
			extJsonBO = JSON.parseObject(workOrderDO.getExtra(), new TypeReference<OrderExtJsonBO>() {
			});
		}
		extJsonBO.setHandleAppealReason(request.getHandleAppealReason());
		workOrderDO.setExtra(JSONObject.toJSON(extJsonBO).toString());

		workOrderBaseService.update(workOrderDO);

		//更新协同小程序订单状态
		LambdaQueryWrapper<WorkOrderReceiverDO> receiverWrapper = new LambdaQueryWrapper<>();
		receiverWrapper.eq(WorkOrderReceiverDO::getWorkOrderNumber, request.getWorkOrderNumber())
			.eq(WorkOrderReceiverDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		List<WorkOrderReceiverDO> workOrderReceiverDOS = workOrderReceiverBaseService.list(receiverWrapper);
		if (CollectionUtils.isNotEmpty(workOrderReceiverDOS)) {
			workOrderReceiverBaseService.batchUpdateOrderStatus(workOrderReceiverDOS, workOrderDO.getDocumentStatus(), workOrderDO.getDocumentScore());
		}

		feiShuSendService.sendOrderHandleFeiShuMsg(workOrderDO);

		// 操作日志
		OperateRecordRequest operateRecordRequest = new OperateRecordRequest();
		operateRecordRequest.setStoreNo(request.getWorkOrderNumber());

		OrderAppealRecordBO updateBefore = new OrderAppealRecordBO();
		updateBefore.setDocumentStatus(StoreWorkOrderStatusEnum.EXPIRED_APPEAL.getDesc());
		operateRecordRequest.setUpdateBefore(JSON.toJSONString(updateBefore));

		OrderAppealRecordBO updateData = new OrderAppealRecordBO();
		updateData.setRecordName(RecordTypeEnum.APPROVAL_ORDER_APPEAL.getDesc());
		updateData.setDocumentStatus(StoreWorkOrderStatusEnum.getByType(workOrderDO.getDocumentStatus()).getDesc());
		updateData.setApproveAppealReason(request.getHandleAppealReason());
		updateData.setAppealStatus(OrderAppealStatusEnum.queryByType(request.getAppealResult()).getDesc());
		operateRecordRequest.setUpdateData(JSON.toJSONString(updateData));

		if (Objects.nonNull(user)) {
			operateRecordRequest.setUpdateFrom(StrUtil.isNotBlank(user.getUserName()) ? user.getUserName() : CommonConstant.OPERATE_SOURCE);
			operateRecordRequest.setUpdateFromCode(String.valueOf(user.getUserId()));
		}
		operateRecordBizService.updateOptRecord(operateRecordRequest);

		return HttpResponseUtil.success(true);
	}


	public BasePageResponse<QueryStoreOperateRecordResponse> queryOperateRecordPage(PaginationRequest<WorkOrderRecordRequest> param) {
		WorkOrderRecordRequest queryParameter = param.getQueryParameter();
		QueryOperateRecordInfoRequest recordInfoRequest = new QueryOperateRecordInfoRequest();
		recordInfoRequest.setStoreNo(queryParameter.getWorkOrderNumber());
		recordInfoRequest.setRecordType(queryParameter.getRecordType());

		PaginationRequest<QueryOperateRecordInfoRequest> request = new PaginationRequest<>();
		request.setPageNum(param.getPageNum());
		request.setPageSize(param.getPageSize());
		request.setQueryParameter(recordInfoRequest);
		BasePageResponse<QueryStoreOperateRecordResponse> response = operateRecordBizService.queryRecordPage(request);
		List<QueryStoreOperateRecordResponse> data = response.getData();
		response.setData(data);
		return response;

	}

}
















